//
//  NetManager3.m
//  03-29-apiDemo-practice
//
//  Created by student on 16/3/29.
//  Copyright © 2016年 niit. All rights reserved.
//

#import "NetManager3.h"

@implementation NetManager3
+(void)requestInfoBymMoney:(int)money
              successBlock:(void(^)(NSString *))successBlock
               failedBlock:(void(^)(NSError *))failBlock
{
    NSString *httpUrl = @"http://apis.baidu.com/apistore/currencyservice/currency";
    NSString *httpArg = [NSString stringWithFormat:@"fromCurrency=CNY&toCurrency=USD&amount=%i",money];
    NSString *urlStr = [[NSString alloc]initWithFormat: @"%@?%@", httpUrl, httpArg];
    NSURL *url = [NSURL URLWithString: urlStr];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 10];
    [request setHTTPMethod: @"GET"];
    [request addValue: @"a47710812a161be75ac6713a123dcbde" forHTTPHeaderField: @"apikey"];
    [NSURLConnection sendAsynchronousRequest: request
                                       queue: [NSOperationQueue mainQueue]
                           completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error){
                               if (error)
                               {
                                   NSLog(@"Httperror: %@%ld", error.localizedDescription, error.code);
                                   failBlock(error);
                               }
                               else
                               {
                                   NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
                                   NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                   NSLog(@"HttpResponseCode:%ld", responseCode);
                                   NSLog(@"HttpResponseBody %@",responseString);
                                   NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                                   NSDictionary *dict1=dict[@"retData"];
                                   NSString *result=[NSString stringWithFormat:@"转化后的金额:%i",dict1[@"USD"]];
                                   successBlock(result);
                               }
                               
    }];
}

@end
